using System;
using System.Web.UI.WebControls;

namespace Framework.Library.Core.Utils.Web.UI
{
    public static class TableUtils
    {
        /// <summary>
        /// Fixes a table so that the last cell in a row has a span that matches the longest row.
        /// </summary>
        /// <param name="table">The table to fix.</param>
        public static void FixColumnSpans(Table table)
        {
            if (table == null)
                throw new ArgumentNullException("table");

            int maxRowWidth = 0;

            // loop through the table's row and get the width of the longest row
            foreach (TableRow row in table.Rows)
            {
                int currentRowWidth = CalculateRowColumnSpan(row);

                if (currentRowWidth > maxRowWidth)
                    maxRowWidth = currentRowWidth;
            }

            // loop through the rows and set the final cell to have a colspan that means
            // it's length matches the longest row
            foreach (TableRow row in table.Rows)
            {
                int currentRowWidth = CalculateRowColumnSpan(row);

                if (currentRowWidth < maxRowWidth)
                    row.Cells[row.Cells.Count - 1].ColumnSpan = maxRowWidth - currentRowWidth + 1;
            }
        }

        /// <summary>
        /// Calculates the row's column span.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <returns>The row's column span.</returns>
        public static int CalculateRowColumnSpan(TableRow row)
        {
            if (row == null)
                throw new ArgumentNullException("row");

            int spanWidth = 0;

            foreach (TableCell cell in row.Cells)
            {
                spanWidth += (cell.ColumnSpan != 0) ? cell.ColumnSpan : 1;
            }

            return spanWidth;
        }
    }
}